import React, { useRef, useEffect, useState, useLayoutEffect } from 'react';
import { useSelector } from 'react-redux';
import { Tag, Spin, Alert } from '@arco-design/web-react';
import { RootState } from '@/store';
import Loading from '@/components/Loading/HorizonLoading';
import Config from '@/config';
import styles from './index.module.less';
import {sendMsg} from '@/api/train'
import { useLeave } from '@/lib/useCommon';
import { callFinished,setAutoHangup } from '@/store/slices/room';
import { useDispatch } from 'react-redux';

const lines: (string | React.ReactNode)[] = [];

// 告警接口调用
const mockAlertReport = (type: 'initial' | 'reply', duration: number) => {
  // 上报告警接口
  sendMsg({
    type: type == 'initial' ? 40 : type == 'reply' ? 10 : 20,
    practice_id: Number(localStorage?.getItem('training_id'))
  })
};

function Conversation(props: React.HTMLAttributes<HTMLDivElement>) {
  const { className, ...rest } = props;
  const msgHistory = useSelector((state: RootState) => state.room.msgHistory);
  const { userId } = useSelector((state: RootState) => state.room.localUser);
  const { isAITalking, isUserTalking } = useSelector((state: RootState) => state.room);
  const isAIReady = msgHistory.length > 0;
  const containerRef = useRef<HTMLDivElement>(null);
  let training_id = localStorage?.getItem('training_id');
  
  // 跟踪组件挂载时间
  const mountedTimeRef = useRef<number>(Date.now());
  // 跟踪已发送的告警状态
  const initialAlertSentRef = useRef(false); // 初始响应告警是否已发送
  const replyAlertSentRef = useRef(false);    // 回复告警是否已发送
  
  // 定时器引用
  const initialTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const replyTimeoutRef = useRef<NodeJS.Timeout | null>(null);

   const leaveRoom = useLeave();
   const dispatch = useDispatch();
  

  useEffect(() => {
    // 监听路由变化

    return () => {
      // 页面销毁，关闭rtc
      dispatch(callFinished({ data:true }));
      leaveRoom().then(()=>{
        dispatch(setAutoHangup({data:false}))
      })
    };
    
  }, []);
  
  const isUserTextLoading = (owner: string) => {
    return owner === userId && isUserTalking;
  };

  const isAITextLoading = (owner: string) => {
    return owner === (Config.BotName + training_id) && isAITalking;
  };

  // useEffect(() => {
  //   const container = containerRef.current;
  //   if (container) {
  //     container.scrollTop = container.scrollHeight - container.clientHeight;
  //   }
  // }, [msgHistory.length]);

  useLayoutEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    // 计算当前是否在底部区域（最后50像素内）
    const isNearBottom = 
      container.scrollHeight - container.scrollTop <= 
      container.clientHeight + 50;

    // 满足以下任一条件则滚动到底部：
    // 1. 是AI发送的新消息
    // 2. 用户停留在底部区域
    const shouldScroll = 
      // 最后一条是AI消息
      (msgHistory.length > 0 && 
      msgHistory[msgHistory.length - 1].user === Config.BotName + training_id) ||
      // 或用户位置在底部区域
      isNearBottom;

    if (shouldScroll) {
      container.scrollTo({
        top: container.scrollHeight,
        behavior: 'smooth'
      });
    }
  }, [msgHistory, msgHistory.length]); 
  
  // AI初始响应超时检测
  useEffect(() => {
    // 记录组件挂载时间
    mountedTimeRef.current = Date.now();
    
    // 设置初始超时检查
    initialTimeoutRef.current = setTimeout(() => {
      // 检查是否已经有AI消息
      const hasAISpoke = msgHistory.some(m => m.user === Config.BotName + training_id);
      
      // 如果已经挂载10秒且AI还没有说话，则触发告警
      if (!hasAISpoke && !initialAlertSentRef.current) {
        mockAlertReport('initial', 10);
        initialAlertSentRef.current = true;
      }
    }, 10000);
    
    // 清除定时器当组件卸载
    return () => {
      if (initialTimeoutRef.current) clearTimeout(initialTimeoutRef.current);
    };
  }, []); // 空依赖数组表示只在组件挂载时执行一次
  
  // 当检测到AI发言时取消初始超时检查
  useEffect(() => {
    const hasAISpoke = msgHistory.some(m => m.user === Config.BotName + training_id);
    
    if (hasAISpoke && initialTimeoutRef.current) {
      clearTimeout(initialTimeoutRef.current);
      initialTimeoutRef.current = null;
      initialAlertSentRef.current = false;
    }
  }, [msgHistory, training_id]); // 依赖消息历史和training_id
  
  // 处理用户消息后的AI回复超时
  useEffect(() => {
    // 跳过空消息历史
    if (msgHistory.length === 0) return;
    
    // 获取最后一条消息
    const lastMessage = msgHistory[msgHistory.length - 1];
    
    // 如果最后一条消息是用户发送的
    if (lastMessage.user === userId) {
      // 取消之前的回复超时计时器
      if (replyTimeoutRef.current) {
        clearTimeout(replyTimeoutRef.current);
        replyTimeoutRef.current = null;
      }
      
      // 重置回复告警状态
      replyAlertSentRef.current = false;
      
      // 设置新的回复超时计时器（10秒）
      replyTimeoutRef.current = setTimeout(() => {
        // 检查是否已经收到AI回复
        const hasAIResponded = msgHistory.some((m, i) => 
          i > msgHistory.indexOf(lastMessage) && m.user === Config.BotName + training_id
        );
        
        if (!hasAIResponded && !replyAlertSentRef.current) {
          mockAlertReport('reply', 10);
          replyAlertSentRef.current = true;
        }
      }, 30000);
    }
    // 如果最后一条消息是AI发送的
    else if (lastMessage.user === Config.BotName + training_id) {
      // AI回复了，清除回复超时定时器
      if (replyTimeoutRef.current) {
        clearTimeout(replyTimeoutRef.current);
        replyTimeoutRef.current = null;
        replyAlertSentRef.current = false;
      }
    }
    
    // 组件卸载时清除定时器
    return () => {
      if (replyTimeoutRef.current) {
        clearTimeout(replyTimeoutRef.current);
        replyTimeoutRef.current = null;
      }
    };
  }, [msgHistory, userId, training_id]); // 依赖消息历史、用户ID和training_id
  
  // 重置告警当AI开始讲话
  useEffect(() => {
    if (isAITalking) {
      // 清除回复超时定时器
      if (replyTimeoutRef.current) {
        clearTimeout(replyTimeoutRef.current);
        replyTimeoutRef.current = null;
      }
      // 重置告警状态
      replyAlertSentRef.current = false;
    }
  }, [isAITalking]);

  return (
    <div ref={containerRef} className={`${styles.conversation} ${className}`} {...rest}>
      {lines.map((line) => line)}
      
      {!isAIReady ? (
        <div className={styles.aiReadying}>
          <Spin size={16} className={styles['aiReading-spin']} />
          AI 准备中, 请稍侯
        </div>
      ) : (
        ''
      )}
      {msgHistory?.map(({ value, user, isInterrupted }, index) => {

        const isUserMsg = user === userId;
        const isRobotMsg = user === Config.BotName + training_id;
        if (!isUserMsg && !isRobotMsg) {
          return '';
        }
        return (
          <div
            className={`${styles.sentence} ${isUserMsg ? styles.user : styles.robot}`}
            key={`msg-${index}`}
            style={{paddingBottom: 0}}
          >
            <div className={styles.content}>
              {value}
              <div className={styles['loading-wrapper']}>
                {isAIReady &&
                (isUserTextLoading(user) || isAITextLoading(user)) &&
                index === msgHistory.length - 1 ? (
                  <Loading gap={3} className={styles.loading} dotClassName={styles.dot} />
                ) : (
                  ''
                )}
              </div>
            </div>
            {/* {!isUserMsg && isInterrupted ? <Tag className={styles.interruptTag}>已打断</Tag> : ''} */}
          </div>
        );
      })}
    </div>
  );
}

export default Conversation;